import {
  store
} from '../../store/store'
import {
  createStoreBindings
} from 'mobx-miniprogram-bindings'
import {
  putUserInfo
} from '../../api/my'

// pages/userInfo/userInfo.js
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
 
  },
  getUserAvatar(e) {
    let userAvatar = e.detail.avatarUrl
    let that = this
    wx.getStorage({
      key: "token",
      success: async (tokenRes) => {
        await putUserInfo({
          token: tokenRes.data,
          data: {
            avatar: userAvatar
          }
        }).then(res => {
          if (res.data.code === 10000) {
            wx.showToast({
              title: '头像上传成功',
            })
            that.editUserInfo({
              nickName: store.userInfo.nickName,
              avatar: userAvatar,
              id: store.userInfo.id
            })
          }
        })
      }
    })

  },
  getUserNickName(e) {
    let nickName = e.detail.value
    let aginNickName = store.userInfo.nickName
    if (nickName === aginNickName) return

    let that = this
    wx.getStorage({
      key: "token",
      success: async (tokenRes) => {
        await putUserInfo({
          token: tokenRes.data,
          data: {
            nickName
          }
        }).then(res => {
          if (res.data.code === 10000) {
            wx.showToast({
              title: '昵称修改成功',
            })
            this.editUserInfo({
              nickName: nickName,
              avatar: store.userInfo.avatar,
              id: store.userInfo.id
            })
          }
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['userInfo'],
      actions: ['editUserInfo']
    })
    wx.getStorage({
      key: 'token',
      fail() {
        wx.redirectTo({
          url: '/pages/login/login',
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})